//
//  Modify_pbxproj.m
//  AutoCompiler_Script
//
//  Created by Vescky on 12-10-23.
//  Copyright (c) 2012年 Vescky. All rights reserved.
//

#import "Modify_pbxproj.h"
#import "RegexKitLite.h"
#import "TabItemDictionary.h"
#import "FileOperator.h"
#import "PathParser.h"

@implementation Modify_pbxproj

//用地址初始化
-(void)initWithProjectPath:(NSString*)path ProjectName:(NSString*)pName
{
    mProjectPath = [path stringByAppendingFormat:@"/%@.xcodeproj/project.pbxproj",pName];
}

//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
//初始化工作区域
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
+ (bool)initWorkSpace {
    PathParser *pp = [PathParser sharePathParser];
    
//    //清空输出目录
//    [[FileOperator shareFileOperator] cleanFolder:pp.outputLogFilesPath];
//    [[FileOperator shareFileOperator] cleanFolder:pp.outputAppPath];
//
    
    NSFileManager *fm = [NSFileManager defaultManager];
    
    NSString *tProjectFilePath = [NSString stringWithFormat:@"%@/%@.xcodeproj",pp.outIosProjectPath,pp.templateProjectName];
    
    //移除之前的工程文件
    if ([fm fileExistsAtPath:tProjectFilePath]) {
        [fm removeItemAtPath:tProjectFilePath error:nil];
    }
    
    //移除之前的bundle
    NSString *bPath = [NSString stringWithFormat:@"%@/%@/%@",pp.outIosProjectPath,pp.templateProjectName,pp.incomeBundleName];
    if ([fm fileExistsAtPath:bPath]) {
        [fm removeItemAtPath:bPath error:nil];
    }
    
    //移除之前的plist文件
    NSString *plistPath = [NSString stringWithFormat:@"%@/%@/%@-Info.plist",pp.outIosProjectPath,pp.templateProjectName,pp.templateProjectName];
    if ([fm fileExistsAtPath:plistPath]) {
        [fm removeItemAtPath:plistPath error:nil];
    }

    NSString *tProjItem = [NSString stringWithFormat:@"%@/%@.xcodeproj",pp.defaultIosProjectPath,pp.templateProjectName];
    NSString *tPlistPath = [NSString stringWithFormat:@"%@/%@/%@-Info.plist",pp.defaultIosProjectPath,pp.templateProjectName,pp.templateProjectName];
//    NSLog(@"%@",tProjectFilePath);
//    NSLog(@"%@",bPath);
//    NSLog(@"%@",tProjItem);
//    NSLog(@"%@",pp.incomeBundlePath);
    
//    if (![fm fileExistsAtPath:tProjItem] || ![fm fileExistsAtPath:pp.incomeBundlePath] || ![fm fileExistsAtPath:tPlistPath]) {
//        return NO;
//    }

    if (![fm fileExistsAtPath:tProjItem] || ![fm fileExistsAtPath:tPlistPath]) {
        NSLog(@"$$$$$$$$$$$$$$$ Error:Default Template can't be empty!! $$$$$$$$$$$$$$$\n");
        return NO;
    }
    if (![fm fileExistsAtPath:pp.incomeBundlePath] ) {
        NSLog(@"$$$$$$$$$$$$$$$ Error:Zip package can't be empty!!! $$$$$$$$$$$$$$$\n");
        return NO;
    }
    
    //复制模板的工程配置文件
    [fm copyItemAtPath:tProjItem toPath:tProjectFilePath error:nil];
    
    //复制plist文件
    [fm copyItemAtPath:tPlistPath toPath:plistPath error:nil];
    
    //复制bundle
    [fm copyItemAtPath:pp.incomeBundlePath toPath:bPath error:nil];

    return YES;
}

//false 为entirely mode，ture为fast mode
+ (bool)initWorkSpaceWithMode:(bool)mode {
    
    PathParser *pp = [PathParser sharePathParser];
    
//    //清空输出目录
//    [[FileOperator shareFileOperator] cleanFolder:pp.outputLogFilesPath];
//    [[FileOperator shareFileOperator] cleanFolder:pp.outputAppPath];

    if (!mode) {
        NSFileManager *fm = [NSFileManager defaultManager];
        //移除之前的模板
        if ([fm fileExistsAtPath:pp.outIosProjectPath]) {
            [fm removeItemAtPath:pp.outIosProjectPath error:nil];
        }
        //移除之前的bundle
        NSString *bPath = [NSString stringWithFormat:@"%@/%@/%@",pp.outIosProjectPath,pp.templateProjectName,pp.incomeBundleName];
        if ([fm fileExistsAtPath:bPath]) {
            [fm removeItemAtPath:bPath error:nil];
        }
        NSString *tItem = pp.defaultIosProjectPath;//[NSString stringWithFormat:@"%@/ios/%@",pp.defaultTemplatePath,pp.templateProjectName];
//        if (![fm fileExistsAtPath:tItem] || ![fm fileExistsAtPath:pp.incomeBundlePath]) {
//            return NO;
//        }
        if (![fm fileExistsAtPath:tItem] ) {
            NSLog(@"$$$$$$$$$$$$$$$ Error:Default Template can't be empty!! $$$$$$$$$$$$$$$\n");
            return NO;
        }
        if (![fm fileExistsAtPath:pp.incomeBundlePath] ) {
            NSLog(@"$$$$$$$$$$$$$$$ Error:Zip package can't be empty!!! $$$$$$$$$$$$$$$\n");
            return NO;
        }

        //复制模板
        [fm copyItemAtPath:tItem toPath:pp.outIosProjectPath error:nil];
        //复制bundle
        [fm copyItemAtPath:pp.incomeBundlePath toPath:bPath error:nil];
    }
    else {
        return [self initWorkSpace];
    }
    
    return YES;
}


//获取Plist的路径
+(NSString*)getPlistPath:(NSString*)pPath
{
    NSArray *arrayPaths = [pPath componentsSeparatedByRegex:@"/"];
    NSString *projectName = [arrayPaths objectAtIndex:([arrayPaths count] - 1)];
    //NSLog(@"Project Name:%@",projectName);
    NSString *resultStr = [pPath stringByAppendingFormat:@"/%@/%@-Info.plist",projectName,projectName];
    //NSLog(@"Plist Path:%@",resultStr);
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:resultStr]) {
        return nil;
    }
    
    return resultStr;
}

//获取.pbxproject的路径
+(NSString*)getPbxprojPath:(NSString*)pPath
{
    NSArray *arrayPaths = [pPath componentsSeparatedByRegex:@"/"];
    NSString *projectName = [arrayPaths objectAtIndex:([arrayPaths count] - 1)];
//    NSLog(@"Project Name:%@",projectName);
    NSString *resultStr = [pPath stringByAppendingFormat:@"/%@.xcodeproj/project.pbxproj",projectName];
//    NSLog(@"project.pbxproj Path:%@",resultStr);
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:resultStr]) {
//        NSLog(@"File not exist!");
        return nil;
    }
    
    return resultStr;
}

//注释含有关键字的行
-(void)noteTheLineOfKey:(NSString*)key
{
    
}

//静态方法，将含有关键字的行注释掉
+(void)noteTheLine:(NSString*)key projectPath:(NSString*)path
{
    //NSString *pPath = [path stringByAppendingFormat:@"/%@.xcodeproj/project.pbxproj",pName];
    NSString *pPath = nil;
    if (path == nil) {
      pPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/project.pbxproj"];
    }
    else
    {
        //根据工程目录获取配置文件位置
        pPath = [self getPbxprojPath:path];
    }
    
    //文件不存在，不能修改
    if (pPath == nil) {
        return;
    }
    
    NSString *handleStr = nil;
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:pPath encoding:NSUTF8StringEncoding error:nil];
    if (str == nil) {
//        NSLog(@"NIL");
        return;
    }
    else{
        NSString *temp = [str stringByReplacingOccurrencesOfRegex:@"\"<" withString:@"\"&lt;"];
        NSString *temp1 = [temp stringByReplacingOccurrencesOfRegex:@"<.*?>" withString:@" "];
        NSString *temp2 = [temp1 stringByReplacingOccurrencesOfRegex:@"&lt;" withString:@"<"];
        handleStr = [temp2 stringByReplacingOccurrencesOfRegex:@"&gt;" withString:@">"];
        //NSLog(@"\n File: \n %@",handleStr);
        //[usefulStr writeToFile:pName atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }

    NSString *keyWord = [NSString stringWithFormat:@".* %@..*\\n",key];
    
    NSString *resultStr = [handleStr stringByReplacingOccurrencesOfRegex:keyWord withString:@" \n"];

   // NSLog(@"\n\n\n\n\n\n\n\n\n%@",resultStr);
    
    [resultStr writeToFile:pPath atomically:YES encoding:NSUTF8StringEncoding error:nil];

}

#pragma mark - 执文件
#pragma mark begin>>>>>>>>>>>
//-------------------- 执文件 ------------------------
//------旧方法，不建议使用
+ (void)deleteFilesWithArray:(NSArray*)_arr projectPath:(NSString*)path {
    if (!_arr || [_arr count] <= 0) {
        return;
    }
    
    NSString *pPath = nil;
    if (path == nil) {
        pPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/project.pbxproj"];
    }
    else
    {
        //根据工程目录获取配置文件位置
        pPath = [self getPbxprojPath:path];
    }
    
    //文件不存在，不能修改
    if (pPath == nil) {
        return;
    }
    
    NSString *handleStr = nil;
    
    NSLog(@">>>>>> delete begin!\n");
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:pPath encoding:NSUTF8StringEncoding error:nil];
    if (str == nil) {
        return;
    }
    else{
        NSString *temp = [str stringByReplacingOccurrencesOfRegex:@"\"<" withString:@"\"&lt;"];
        NSString *temp1 = [temp stringByReplacingOccurrencesOfRegex:@"<.*?>" withString:@" "];
        NSString *temp2 = [temp1 stringByReplacingOccurrencesOfRegex:@"&lt;" withString:@"<"];
        handleStr = [temp2 stringByReplacingOccurrencesOfRegex:@"&gt;" withString:@">"];
    }
    
    NSString *resultStr = handleStr;
    for (int i = 0; i < [_arr count]; i++) {
        NSString *keyWord = [NSString stringWithFormat:@".* %@..*\\n",[_arr objectAtIndex:i]];
        resultStr = [resultStr stringByReplacingOccurrencesOfRegex:keyWord withString:@" \n"];
    }
    
    [resultStr writeToFile:pPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSLog(@">>>>>> delete done!!!\n");
}

//原始方法删除内容中的文件
+ (NSString*)deleteFilesWithArray:(NSArray*)fileList Content:(NSString*)content {
    if (!fileList || [fileList count] <= 0) {
        return nil;
    }
    
    if (content == nil) {
        return nil;
    }
    
    NSString *resultStr = @"\n";
    NSArray *arr = [content componentsSeparatedByString:@"\n"];
    for (int i = 0; i < [arr count]; i++) {
        NSString *str = [arr objectAtIndex:i];
        if (![str stringByMatching:@"\\."]) {
            resultStr = [resultStr stringByAppendingFormat:@"%@\n",str];
            continue;
        }
        
        bool needToDel = NO;
        for (int j = 0; j < [fileList count]; j++) {
            NSString *cFile = [fileList objectAtIndex:j];

            if ([[str componentsSeparatedByString:[NSString stringWithFormat:@" %@ ",cFile]] count] > 1) {
                needToDel = YES;
                break;
            }
            
        }
        if (!needToDel) {
            resultStr = [resultStr stringByAppendingFormat:@"%@\n",str];
        }
        else {
            resultStr = [resultStr stringByAppendingFormat:@"\t\t/* >>>>>>>>>>>>> Modified by Vk <<<<<<<<<<<<<< */\n"];
        }
    }
    
    return resultStr;
}

//删除datamodel的方法
+ (NSString*)deleteDataModelWithArray:(NSArray*)tabAndLayoutArr Content:(NSString*)content {
    if (!tabAndLayoutArr || [tabAndLayoutArr count] <= 0) {
        return content;
    }
    
    if (content == nil) {
        return nil;
    }
    //解析出那些datamodel需要删除
    NSMutableArray *allDatamodelFileList = [TabItemDictionary searchForXcmodelInHomePageAndTabs];//[TabItemDictionary searchForXcmodelInTabName:nil layoutName:nil];
    NSMutableArray *reserveDatamodelList = [[NSMutableArray alloc] init];
    for (int i = 0; i < [tabAndLayoutArr count]; i++) {
        NSDictionary *dict = [tabAndLayoutArr objectAtIndex:i];
        NSArray *tList = [TabItemDictionary searchForXcmodelInTabName:[dict objectForKey:@"tabName"] layoutName:[dict objectForKey:@"layout"]];
        if (tList && [tList count] > 0) {
            for (int j = 0; j < [tList count]; j++) {
                [reserveDatamodelList addObject:[tList objectAtIndex:j]];
            }
        }
    }
    
    for (int i = 0; i < [reserveDatamodelList count]; i++) {
        NSString *dName = [reserveDatamodelList objectAtIndex:i];
        for (int j = 0; j < [allDatamodelFileList count]; j++) {
            if ([[allDatamodelFileList objectAtIndex:j] isEqualToString:dName]) {
                [allDatamodelFileList removeObjectAtIndex:j];
                break;
            }
        }
    }
    
    NSMutableArray *fileList = allDatamodelFileList;
    if (!fileList || [fileList count] <= 0) {
        return content;
    }
    
    
    //modify head -- PBXBuildFile,PBXFileReference
    NSString *headContent = [content stringByMatching:@"Begin PBXBuildFile section(?:.|[\r\n])*?End PBXFileReference section"];
    NSArray *headArr = [headContent componentsSeparatedByString:@"\n"];
    NSMutableArray *headResultArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [headArr count]; i ++) {
        NSString *hStr = [self deleteFilesWithArray:fileList Content:[headArr objectAtIndex:i]];
        [headResultArr addObject:hStr];
    }
    
    NSString *hResultStr = @"\n";
    for (int i = 0; i < [headArr count];  i++) {
        hResultStr = [hResultStr stringByAppendingFormat:@"%@\n",[headResultArr objectAtIndex:i]];
    }
    
    content = [content stringByReplacingOccurrencesOfRegex:@"Begin PBXBuildFile section(?:.|[\r\n])*?End PBXFileReference section" withString:hResultStr];
    
    //modify tail -- XCVersionGroup
    NSString *tailContent = [content stringByMatching:@"Begin XCVersionGroup section(?:.|[\r\n])*?End XCVersionGroup section"];
    NSMutableArray *tailResultArr = [[NSMutableArray alloc] initWithArray:[tailContent componentsSeparatedByString:@"};"]];
    if ([tailResultArr count] > 0) {
        for (int i = 0; i < [fileList count]; i++) {
            NSString *fStr = [fileList objectAtIndex:i];
            fStr = [fStr stringByReplacingOccurrencesOfString:@"." withString:@"\\."];
            for (int j = 0; j < [tailResultArr count]; j++) {
                NSString *cString = [tailResultArr objectAtIndex:j];
                if ([cString stringByMatching:fStr]) {
                    [tailResultArr replaceObjectAtIndex:j withObject:@"\t\t/* >>>>>>>>>>>>> Modified by Vk <<<<<<<<<<<<<< */\n"];
                    break;
                }
            }
        }
    }
    
    NSString *tResultStr = @"\n";
    for (int i = 0; i < [tailResultArr count]; i++) {
        NSString *str = [tailResultArr objectAtIndex:i];
        if ([str stringByMatching:@"Modified by Vk"]) {
            tResultStr = [tResultStr stringByAppendingFormat:@"%@",str];
        }
        else {
            tResultStr = [tResultStr stringByAppendingFormat:@"%@};",str];
        }
    }
    
    if (![tResultStr stringByMatching:@"Begin XCVersionGroup section"]) {
        tResultStr = [NSString stringWithFormat:@"Begin XCVersionGroup section */ \n %@",tResultStr];
    }
    
    if (![tResultStr stringByMatching:@"End XCVersionGroup section"]) {
        tResultStr = [NSString stringWithFormat:@"%@\n/* End XCVersionGroup section",tResultStr];
    }
    
    content = [content stringByReplacingOccurrencesOfRegex:@"Begin XCVersionGroup section(?:.|[\r\n])*?End XCVersionGroup section" withString:tResultStr];
    
    //modify source -- PBXSourcesBuildPhase
    NSString *sourceFileContent = [content stringByMatching:@"Begin PBXSourcesBuildPhase section(?:.|[\r\n])*?End PBXSourcesBuildPhase section"];
    NSArray *sourceArr = [sourceFileContent componentsSeparatedByString:@"\n"];
    NSMutableArray *sourceResultArr = [[NSMutableArray alloc] init];
    for (int i = 0; i < [sourceArr count]; i++) {
        NSString *sStr = [self deleteFilesWithArray:fileList Content:[sourceArr objectAtIndex:i]];
        [sourceResultArr addObject:sStr];
    }
    NSString *sResultStr = @"\n";
    for (int i = 0; i < [sourceResultArr count]; i++) {
        sResultStr = [sResultStr stringByAppendingFormat:@"%@\n",[sourceResultArr objectAtIndex:i]];
    }
    
    content = [content stringByReplacingOccurrencesOfRegex:@"Begin PBXSourcesBuildPhase section(?:.|[\r\n])*?End PBXSourcesBuildPhase section" withString:sResultStr];
    
    return content;
}

//------- 新方法，可选用快速模式和完全模式 _arr,文件名清单------
+ (void)deleteFilesWithArray:(NSArray*)_arr usingFastMode:(bool)fastMode projectPath:(NSString*)path {
    if (!fastMode) {
        [self deleteFilesWithArray:_arr projectPath:path];
        return;
    }
    
    if (!_arr || [_arr count] <= 0) {
        return;
    }
    
    NSString *pPath = nil;
    if (path == nil) {
        pPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/project.pbxproj"];
    }
    else
    {
        //根据工程目录获取配置文件位置
        pPath = [self getPbxprojPath:path];
    }
    
    //文件不存在，不能修改
    if (pPath == nil) {
        return;
    }
    
    NSString *handleStr = nil;
    
    NSLog(@">>>>>> delete begin!\n");
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:pPath encoding:NSUTF8StringEncoding error:nil];
    if (str == nil) {
//        NSLog(@"NIL");
        return;
    }
    else{
        NSString *temp = [str stringByReplacingOccurrencesOfRegex:@"\"<" withString:@"\"&lt;"];
        NSString *temp1 = [temp stringByReplacingOccurrencesOfRegex:@"<.*?>" withString:@" "];
        NSString *temp2 = [temp1 stringByReplacingOccurrencesOfRegex:@"&lt;" withString:@"<"];
        handleStr = [temp2 stringByReplacingOccurrencesOfRegex:@"&gt;" withString:@">"];
    }
    
    NSString *_regex = @"Begin PBXBuildFile section(?:.|[\r\n])*?End PBXBuildFile section";
    NSString *buildFileSection = [handleStr stringByMatching:_regex];
    
    //---------- New Logic begin
    NSArray *filesArray = [buildFileSection componentsSeparatedByString:@"\n"];
    NSMutableDictionary *filesDict = [[NSMutableDictionary alloc] init];
    
    for (int  i = 1; i < [filesArray count] - 1; i++) {
        NSString *fName = [[filesArray objectAtIndex:i] stringByMatching:@"/\\*.*?\\.\\w+"];
        fName = [fName stringByReplacingOccurrencesOfString:@"/* " withString:@""];
        
        NSString *fId = [[filesArray objectAtIndex:i] stringByMatching:@"\\w+ /"];
        fId = [fId stringByReplacingOccurrencesOfString:@" /" withString:@""];
        
        if (fName && fId) {
            NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:fName,@"name",fId,@"id",[filesArray objectAtIndex:i],@"value", nil];
            [filesDict setObject:dict forKey:fName];
        }
    }
    
    NSString *testString = @"Begin PBXBuildFile section */\n";

    for (int i = 0; i < [_arr count]; i++) {
        NSString *readyForDeleteString = [_arr objectAtIndex:i];
        [filesDict removeObjectForKey:readyForDeleteString];
    }
    
    NSEnumerator *enumDict = [filesDict keyEnumerator];
    for (NSString *_key in enumDict) {
        testString = [testString stringByAppendingFormat:@"%@\n",[[filesDict objectForKey:_key] objectForKey:@"value"]];
    }
    
    testString = [testString stringByAppendingString:@"\n/* End PBXBuildFile section"];
    
    NSString *resultStr = [handleStr stringByReplacingOccurrencesOfRegex:_regex withString:testString];

    [resultStr writeToFile:pPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSLog(@">>>>>> delete done!!!\n");
}

//#define PART1
//#define PART2
#define PART3
//#define PART4
//#define PART5
#define PARTE

//_arr结构：dictionary,dictionary,...  dictionary-- (NSString)tabName (NSString)layout
+ (void)deleteFilesExceptArray:(NSArray*)_arr fileList:(NSArray*)fileList projectPath:(NSString*)path {
    if (!_arr || [_arr count] <= 0) {
        return;
    }
    
    NSString *pPath = nil;
    if (path == nil) {
        pPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/project.pbxproj"];
    }
    else
    {
        //根据工程目录获取配置文件位置
        pPath = [self getPbxprojPath:path];
    }
    
    //文件不存在，不能修改
    if (pPath == nil) {
        return;
    }
    
    NSString *handleStr = nil;
    
    NSLog(@">>>>>> delete begin!\n");
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:pPath encoding:NSUTF8StringEncoding error:nil];
    if (str == nil) {
        return;
    }
    else{//解析htm标签
        NSString *temp = [str stringByReplacingOccurrencesOfRegex:@"\"<" withString:@"\"&lt;"];
        NSString *temp1 = [temp stringByReplacingOccurrencesOfRegex:@"<.*?>" withString:@" "];
        NSString *temp2 = [temp1 stringByReplacingOccurrencesOfRegex:@"&lt;" withString:@"<"];
        handleStr = [temp2 stringByReplacingOccurrencesOfRegex:@"&gt;" withString:@">"];
        //NSLog(@"\n File: \n %@",handleStr);
        //[usefulStr writeToFile:pName atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    
    NSString *resultStr = handleStr;
#pragma mark Part1 PBXBuildFile Section begin
#ifdef PART1
    [self deleteFilesWithArray:fileList usingFastMode:YES projectPath:path];
#endif
#pragma mark Part1 PBXBuildFile Section end
    
#pragma mark Part2 PBXFileReference Section begin
#ifdef PART2
    NSString *frString = [handleStr stringByMatching:@"Begin PBXFileReference section(?:.|[\r\n])*?End PBXFileReference section"];
    NSMutableDictionary *frDict = [self getGroupListDict:frString useFileNameAsMainKey:YES fileNameRegex:@"/\\*.*?\\.\\w+" separator:@"\n"];
    
    NSString *frResultString = @"Begin PBXFileReference section */\n";
    
    for (int i = 0; i < [fileList count]; i++) {
        NSString *readyForDeleteString = [fileList objectAtIndex:i];
        [frDict removeObjectForKey:readyForDeleteString];
    }
    
    NSEnumerator *enumDict = [frDict keyEnumerator];
    for (NSString *_key in enumDict) {
        frResultString = [frResultString stringByAppendingFormat:@"%@\n",[[frDict objectForKey:_key] objectForKey:@"value"]];
    }
    
    frResultString = [frResultString stringByAppendingString:@"\n/* End PBXFileReference section"];
    
    //替换进入result
    resultStr = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin PBXFileReference section(?:.|[\r\n])*?End PBXFileReference section" withString:frResultString];
#endif
#pragma mark Part2 PBXFileReference Section end
    
    
#pragma mark Part3 PBXGroup Section begin
#ifdef PART3
    NSString *groupString = [handleStr stringByMatching:@"Begin PBXGroup section(?:.|[\r\n])*?End PBXGroup section"];
    NSMutableDictionary *groupDict = [self getProjGroupSectionListWithContent:groupString];
    
    NSMutableArray *tabsGroupIdList = [self getGroupListFromContent:[self getGroupContentFromTabName:@"Tab" InPbxprojString:groupString]];
    NSMutableArray *homepageGroupIdList = [self getGroupListFromContent:[self getGroupContentFromTabName:@"Home_Page" InPbxprojString:groupString]];
    
    //获取所有layout的ID
    NSMutableArray *totalIdList = [[NSMutableArray alloc] init];
    for (int i = 0; i < [homepageGroupIdList count]; i++) {
        NSString *tabId = [[homepageGroupIdList objectAtIndex:i] objectForKey:@"id"];
        if (tabId) {
            [totalIdList addObject:tabId];
        }
    }
    for (int i = 0; i < [tabsGroupIdList count]; i++) {
        NSString *_tabId = [[tabsGroupIdList objectAtIndex:i] objectForKey:@"id"];
         NSMutableArray *subTabsIdList = [self getGroupListFromContent:[self getGroupContentFromId:_tabId InPbxprojString:groupString]];
        for (int j = 0; j < [subTabsIdList count]; j++) {
            NSString *_subTabId = [[subTabsIdList objectAtIndex:j] objectForKey:@"id"];
            if (_subTabId) {
                [totalIdList addObject:_subTabId];
            }
        }
    }
    
    NSMutableArray *reserveIdList = [[NSMutableArray alloc] init];
    for (int i = 0; i < [_arr count]; i++) {
        NSDictionary *_tDict = [_arr objectAtIndex:i];
        NSString *_tLayout = [_tDict objectForKey:@"layout"];
        if ([[_tDict objectForKey:@"tabName"] isEqualToString:@"Home_Page"]) {
            //HomePage的情况
            for (int j = 0; j < [homepageGroupIdList count]; j++) {
                NSDictionary *hDict = [homepageGroupIdList objectAtIndex:j];
                if ([[hDict objectForKey:@"name"] isEqualToString:_tLayout]) {
                    [reserveIdList addObject:[hDict objectForKey:@"id"]];
                    break;
                }
            }
        }
        else {
            //其他tab的情况
            NSString *_tTabId = @"";
            for (int k = 0; k < [tabsGroupIdList count]; k++) {
                NSDictionary *_ttDict = [tabsGroupIdList objectAtIndex:k];
                if ([[_ttDict objectForKey:@"name"] isEqualToString:[_tDict objectForKey:@"tabName"]]) {
                    _tTabId = [_ttDict objectForKey:@"id"];
                    break;
                }
            }
            
            if (_tTabId.length <= 0) {
                continue;
            }
            
            NSMutableArray *subTabsIdList = [self getGroupListFromContent:[self getGroupContentFromId:_tTabId InPbxprojString:groupString]];
            for (int m = 0; m < [subTabsIdList count]; m++) {
                NSDictionary *_subDict = [subTabsIdList objectAtIndex:m];
                if ([[_subDict objectForKey:@"name"] isEqualToString:_tLayout]) {
                    [reserveIdList addObject:[_subDict objectForKey:@"id"]];
                    break;
                }
            }
            
        }
    }
    
    //需要删除的Layout ID数组
    NSMutableArray *deleArray = [[NSMutableArray alloc] initWithArray:totalIdList];
    for (int i = 0; i < [reserveIdList count]; i++) {
        NSString *rId = [reserveIdList objectAtIndex:i];
        [deleArray removeObject:rId];
    }
    
    for (int i = 0; i < [deleArray count]; i++) {
        NSString *readyForDeleteString = [deleArray objectAtIndex:i];
        [groupDict removeObjectForKey:readyForDeleteString];
    }
    
    NSString *groupResultString = @"Begin PBXGroup section */\n";
    NSEnumerator *enumDictG = [groupDict keyEnumerator];
    for (NSString *_key in enumDictG) {
        NSString *itemStr = [[groupDict objectForKey:_key] objectForKey:@"value"];
        itemStr = [itemStr stringByReplacingOccurrencesOfString:@"Begin PBXGroup section */" withString:@""];
        groupResultString = [groupResultString stringByAppendingFormat:@"%@\n",itemStr];
    }
    
    groupResultString = [groupResultString stringByAppendingString:@"/* End PBXGroup section"];
    
    resultStr = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin PBXGroup section(?:.|[\r\n])*?End PBXGroup section" withString:groupResultString];
#endif
#pragma mark Part3 PBXGroup Section end
    
#pragma mark - Part Extra begin //只与part3相配合使用
#ifdef PARTE
    NSString *eGroupString = [resultStr stringByMatching:@"Begin PBXGroup section(?:.|[\r\n])*?End PBXGroup section"];
    NSString *extraStr = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin PBXGroup section(?:.|[\r\n])*?End PBXGroup section" withString:@"PBXGroup section"];
    NSString *extraResult = [self deleteFilesWithArray:fileList Content:extraStr];
    resultStr = [extraResult stringByReplacingOccurrencesOfRegex:@"PBXGroup section" withString:eGroupString];
#endif
#pragma mark - Part Extra end
    
#pragma mark Part4 PBXResourceBiuldPhase Section begin
#ifdef PART4
    NSString *resourceString = [handleStr stringByMatching:@"Begin PBXResourcesBuildPhase section(?:.|[\r\n])*?End PBXResourcesBuildPhase section"];
    NSString *filesSource = [resourceString stringByMatching:@"files = \\((?:.|[\r\n])*?\\);"];
    filesSource = [filesSource stringByReplacingOccurrencesOfString:@"files = (" withString:@""];
    filesSource = [filesSource stringByReplacingOccurrencesOfString:@");" withString:@""];
    
    NSMutableDictionary *resourceDict = [self getGroupListDict:filesSource useFileNameAsMainKey:YES fileNameRegex:@"/\\*.*?\\.\\w+" separator:@"\n"];
    
    NSString *resourceResultString = @"files = (\n";
    
    for (int i = 0; i < [fileList count]; i++) {
        NSString *readyForDeleteString = [fileList objectAtIndex:i];
        [resourceDict removeObjectForKey:readyForDeleteString];
    }
    
    NSEnumerator *resourceEnumDict = [resourceDict keyEnumerator];
    for (NSString *_key in resourceEnumDict) {
        resourceResultString = [resourceResultString stringByAppendingFormat:@"%@\n",[[resourceDict objectForKey:_key] objectForKey:@"value"]];
    }
    
    resourceResultString = [resourceResultString stringByAppendingString:@");"];
    
    resourceResultString = [resourceString stringByReplacingOccurrencesOfRegex:@"files = \\((?:.|[\r\n])*?\\);" withString:resourceResultString];
    
    //替换进入result
    resultStr = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin PBXResourcesBuildPhase section(?:.|[\r\n])*?End PBXResourcesBuildPhase section" withString:resourceResultString];
#endif
    
#pragma mark Part4 PBXResourceBiuldPhase Section end
    
#pragma mark Part5 PBXSourceBiuldPhase Section begin
#ifdef PART5
    NSString *sourceString = [handleStr stringByMatching:@"Begin PBXSourcesBuildPhase section(?:.|[\r\n])*?End PBXSourcesBuildPhase section"];
    NSString *sfilesSource = [sourceString stringByMatching:@"files = \\((?:.|[\r\n])*?\\);"];
    sfilesSource = [sfilesSource stringByReplacingOccurrencesOfString:@"files = (" withString:@""];
    sfilesSource = [sfilesSource stringByReplacingOccurrencesOfString:@");" withString:@""];
    
    NSMutableDictionary *sourceDict = [self getGroupListDict:sfilesSource useFileNameAsMainKey:YES fileNameRegex:@"/\\*.*?\\.\\w+" separator:@"\n"];
    
    NSString *sourceResultString = @"files = (\n";
    
    for (int i = 0; i < [fileList count]; i++) {
        NSString *readyForDeleteString = [fileList objectAtIndex:i];
        [sourceDict removeObjectForKey:readyForDeleteString];
    }
    
    NSEnumerator *sourceEnumDict = [sourceDict keyEnumerator];
    for (NSString *_key in sourceEnumDict) {
        sourceResultString = [sourceResultString stringByAppendingFormat:@"%@\n",[[sourceDict objectForKey:_key] objectForKey:@"value"]];
    }
    
    sourceResultString = [sourceResultString stringByAppendingString:@");"];
    
    sourceResultString = [sourceString stringByReplacingOccurrencesOfRegex:@"files = \\((?:.|[\r\n])*?\\);" withString:sourceResultString];
    
    //替换进入result
    resultStr = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin PBXSourcesBuildPhase section(?:.|[\r\n])*?End PBXSourcesBuildPhase section" withString:sourceResultString];
    
#endif
#pragma mark Part5 PBXSourceBiuldPhase Section end
//  旧方法，简单的搜索全部，然后替换
//    for (int i = 0; i < [fileList count]; i++) {
//        NSString *keyWord = [NSString stringWithFormat:@".* %@..*\\n",[fileList objectAtIndex:i]];
//        resultStr = [resultStr stringByReplacingOccurrencesOfRegex:keyWord withString:@" \n"];
//    }
//
    [resultStr writeToFile:pPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSLog(@">>>>>> delete done!!!\n");
}

#pragma mark - 
#pragma mark - !!!!!!!执文件算法-2013.1.15完成，目前为止最优化的算法!!!!!
+ (void)deleteFilesExceptArray:(NSArray*)_arr fileList:(NSArray*)fileList usingFastMode:(bool)fastMode projectPath:(NSString*)path {
    if (!_arr || [_arr count] <= 0) {
        return;
    }
    
    NSString *pPath = nil;
    if (path == nil) {
        pPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/project.pbxproj"];
    }
    else
    {
        //根据工程目录获取配置文件位置
        pPath = [self getPbxprojPath:path];
    }
    
    //文件不存在，不能修改
    if (pPath == nil) {
        return;
    }
    
    NSString *handleStr = nil;
    
    NSLog(@">>>>>> delete begin!\n");
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:pPath encoding:NSUTF8StringEncoding error:nil];
    if (str == nil) {
//        NSLog(@"NIL");
        return;
    }
    else{//解析htm标签
        NSString *temp = [str stringByReplacingOccurrencesOfRegex:@"\"<" withString:@"\"&lt;"];
        NSString *temp1 = [temp stringByReplacingOccurrencesOfRegex:@"<.*?>" withString:@" "];
        NSString *temp2 = [temp1 stringByReplacingOccurrencesOfRegex:@"&lt;" withString:@"<"];
        handleStr = [temp2 stringByReplacingOccurrencesOfRegex:@"&gt;" withString:@">"];
        //NSLog(@"\n File: \n %@",handleStr);
        //[usefulStr writeToFile:pName atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    
    NSString *resultStr = handleStr;

    if (fastMode) {
#pragma mark fast mode
        NSString *eBuildString = [resultStr stringByMatching:@"Begin PBXBuildFile section(?:.|[\r\n])*?End PBXBuildFile section"];
        NSString *extraStr = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin PBXBuildFile section(?:.|[\r\n])*?End PBXBuildFile section" withString:@"PBXBuildFile section"];
        NSString *extraResult = [self deleteFilesWithArray:fileList Content:eBuildString];
        resultStr = [extraStr stringByReplacingOccurrencesOfRegex:@"PBXBuildFile section" withString:extraResult];
    }
    else {
#pragma mark ## delete Group Section
        NSString *groupString = [handleStr stringByMatching:@"Begin PBXGroup section(?:.|[\r\n])*?End PBXGroup section"];
        NSMutableDictionary *groupDict = [self getProjGroupSectionListWithContent:groupString];
        
        NSMutableArray *tabsGroupIdList = [self getGroupListFromContent:[self getGroupContentFromTabName:@"Tab" InPbxprojString:groupString]];
        NSMutableArray *homepageGroupIdList = [self getGroupListFromContent:[self getGroupContentFromTabName:@"Home_Page" InPbxprojString:groupString]];
        
        //获取所有layout的ID
        NSMutableArray *totalIdList = [[NSMutableArray alloc] init];
        for (int i = 0; i < [homepageGroupIdList count]; i++) {
            NSString *tabId = [[homepageGroupIdList objectAtIndex:i] objectForKey:@"id"];
            if (tabId) {
                [totalIdList addObject:tabId];
            }
        }
        for (int i = 0; i < [tabsGroupIdList count]; i++) {
            NSString *_tabId = [[tabsGroupIdList objectAtIndex:i] objectForKey:@"id"];
            NSMutableArray *subTabsIdList = [self getGroupListFromContent:[self getGroupContentFromId:_tabId InPbxprojString:groupString]];
            for (int j = 0; j < [subTabsIdList count]; j++) {
                NSString *_subTabId = [[subTabsIdList objectAtIndex:j] objectForKey:@"id"];
                if (_subTabId) {
                    [totalIdList addObject:_subTabId];
                }
            }
        }
        
        NSMutableArray *reserveIdList = [[NSMutableArray alloc] init];
        for (int i = 0; i < [_arr count]; i++) {
            NSDictionary *_tDict = [_arr objectAtIndex:i];
            NSString *_tLayout = [_tDict objectForKey:@"layout"];
            if ([[_tDict objectForKey:@"tabName"] isEqualToString:@"Home_Page"]) {
                //HomePage的情况
                for (int j = 0; j < [homepageGroupIdList count]; j++) {
                    NSDictionary *hDict = [homepageGroupIdList objectAtIndex:j];// || [[[hDict objectForKey:@"name"] lowercaseString] isEqualToString:@"base"]
                    if ([[hDict objectForKey:@"name"] isEqualToString:_tLayout] ) {
                        [reserveIdList addObject:[hDict objectForKey:@"id"]];
                        break;
                    }
                }
            }
            else {
                //其他tab的情况
                NSString *_tTabId = @"";
                for (int k = 0; k < [tabsGroupIdList count]; k++) {
                    NSDictionary *_ttDict = [tabsGroupIdList objectAtIndex:k];
                    if ([[_ttDict objectForKey:@"name"] isEqualToString:[_tDict objectForKey:@"tabName"]]) {
                        _tTabId = [_ttDict objectForKey:@"id"];
                        break;
                    }
                }
                
                if (_tTabId.length <= 0) {
                    continue;
                }
                
                NSMutableArray *subTabsIdList = [self getGroupListFromContent:[self getGroupContentFromId:_tTabId InPbxprojString:groupString]];
                for (int m = 0; m < [subTabsIdList count]; m++) {
                    NSDictionary *_subDict = [subTabsIdList objectAtIndex:m];//|| [[[_subDict objectForKey:@"name"] lowercaseString] isEqualToString:@"base"]
                    if ([[_subDict objectForKey:@"name"] isEqualToString:_tLayout] ) {
                        [reserveIdList addObject:[_subDict objectForKey:@"id"]];
                        break;
                    }
                }
                
            }
        }

        //需要删除的Layout ID数组
        NSMutableArray *deleArray = [[NSMutableArray alloc] initWithArray:totalIdList];
        for (int i = 0; i < [reserveIdList count]; i++) {
            NSString *rId = [reserveIdList objectAtIndex:i];
            [deleArray removeObject:rId];
        }
        
        for (int i = 0; i < [deleArray count]; i++) {
            NSString *readyForDeleteString = [deleArray objectAtIndex:i];
            [groupDict removeObjectForKey:readyForDeleteString];
        }
        
        NSString *groupResultString = @"Begin PBXGroup section */\n";
        NSEnumerator *enumDictG = [groupDict keyEnumerator];
        for (NSString *_key in enumDictG) {
            NSString *itemStr = [[groupDict objectForKey:_key] objectForKey:@"value"];
            itemStr = [itemStr stringByReplacingOccurrencesOfString:@"Begin PBXGroup section */" withString:@""];
            groupResultString = [groupResultString stringByAppendingFormat:@"%@\n",itemStr];
        }
        
        groupResultString = [groupResultString stringByAppendingString:@"/* End PBXGroup section"];
        
        resultStr = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin PBXGroup section(?:.|[\r\n])*?End PBXGroup section" withString:groupResultString];
        
#pragma mark delete other Seciont
        NSString *eGroupString = [resultStr stringByMatching:@"Begin PBXGroup section(?:.|[\r\n])*?End PBXGroup section"];
        NSString *extraStr = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin PBXGroup section(?:.|[\r\n])*?End PBXGroup section" withString:@"PBXGroup section"];
        NSString *extraResult = [self deleteFilesWithArray:fileList Content:extraStr];
        resultStr = [extraResult stringByReplacingOccurrencesOfRegex:@"PBXGroup section" withString:eGroupString];
#pragma mark delete datamodel
//        NSString *datamodelString = [resultStr stringByMatching:@"Begin XCVersionGroup section(?:.|[\r\n])*?End XCVersionGroup section"];
//        NSString *eDatamodelString = [resultStr stringByReplacingOccurrencesOfRegex:@"Begin XCVersionGroup section(?:.|[\r\n])*?End XCVersionGroup section" withString:@"XCVersionGroup section"];
//        NSString *datamodelResult = [self deleteFilesWithArray:fileList Content:datamodelString];
//        resultStr = [eDatamodelString stringByReplacingOccurrencesOfRegex:@"XCVersionGroup section" withString:datamodelResult];
        resultStr = [self deleteDataModelWithArray:_arr Content:resultStr];
    }
    
    [resultStr writeToFile:pPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSLog(@">>>>>> delete done!\n");
}

#pragma mark ## some Funtions
+ (NSMutableDictionary*)getGroupListDict:(NSString*)content useFileNameAsMainKey:(bool)_mainKey fileNameRegex:(NSString*)fRegex separator:(NSString*)seperator {
    NSArray *filesArray = [content componentsSeparatedByString:seperator];
    NSMutableDictionary *filesDict = [[NSMutableDictionary alloc] init];
    
    for (int  i = 0; i < [filesArray count]; i++) {
        NSString *indexOfArr = [filesArray objectAtIndex:i];
        
        NSString *fId = [indexOfArr stringByMatching:@"\\w+ /"];
        fId = [fId stringByReplacingOccurrencesOfString:@"/" withString:@""]; 
        fId = [fId stringByReplacingOccurrencesOfString:@" " withString:@""]; 
        
        NSString *value = [NSString stringWithFormat:@"%@\n%@",[filesArray objectAtIndex:i],seperator];
        
        if (fId) {
            NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:fId,@"id",value,@"value", nil];
            if (!_mainKey) {
                [filesDict setObject:dict forKey:fId];
            }
            else {
                NSString *fName = [[filesArray objectAtIndex:i] stringByMatching:fRegex];
                fName = [fName stringByReplacingOccurrencesOfString:@" " withString:@""];
                fName = [fName stringByReplacingOccurrencesOfString:@"*" withString:@""];
                fName = [fName stringByReplacingOccurrencesOfString:@"/" withString:@""];
                fName = [fName stringByReplacingOccurrencesOfString:@"," withString:@""];
                fName = [fName stringByReplacingOccurrencesOfString:@";" withString:@""];
                if (fName) {
                   [filesDict setObject:dict forKey:fName];
                }
            }
        
        }
    }
    return filesDict;
}


+ (NSMutableDictionary*)getProjGroupSectionListWithContent:(NSString*)content {
    NSString *seperator = @"};";
    NSArray *filesArray = [content componentsSeparatedByString:seperator];
    NSMutableDictionary *filesDict = [[NSMutableDictionary alloc] init];
    
    for (int  i = 0; i < [filesArray count]; i++) {
        NSString *indexOfArr = [filesArray objectAtIndex:i];
        
        NSString *fId = [indexOfArr stringByMatching:@"\\w+.*?= \\{"];
        fId = [fId stringByReplacingOccurrencesOfRegex:@"/.*?/" withString:@""];
        fId = [fId stringByReplacingOccurrencesOfString:@"=" withString:@""];
        fId = [fId stringByReplacingOccurrencesOfString:@"{" withString:@""];
        fId = [fId stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        NSString *value = [NSString stringWithFormat:@"%@\n%@",[filesArray objectAtIndex:i],seperator];
        
        if (fId) {
            NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:fId,@"id",value,@"value", nil];
            [filesDict setObject:dict forKey:fId];
        }
    }
    return filesDict;
}


+ (bool)isPbxprojIdDirectory:(NSString*)_pId InPbxprojString:(NSString*)_pString {
    if (!_pString || _pString.length <= 0) {
        return NO;
    }
    
    NSString *line;
    if (_pId && _pId.length > 0) {
        NSString *regex = [NSString stringWithFormat:@"%@.*?,",_pId];
        line = [_pString stringByMatching:regex];
    }
    else {
        line = _pString;
    }
     
    NSString *result = [line stringByMatching:@"\\."];
    if (result && result.length > 0) {
        return NO;
    }
    return YES;
}

+ (NSString*)getGroupContentFromId:(NSString*)_pId InPbxprojString:(NSString*)_pString {
    NSString *regex = [NSString stringWithFormat:@".*?%@.*?=(?:.|[\r\n])*?\\};",_pId];
    NSString *content = [_pString stringByMatching:regex];
    return content;
}

+ (NSString*)getGroupContentFromTabName:(NSString*)_tabName InPbxprojString:(NSString*)_pString {
    NSString *regex = [NSString stringWithFormat:@".*?/\\* %@ \\*/ = \\{(?:.|[\r\n])*?path = %@;(?:.|[\r\n])*?\\};",_tabName,_tabName];
    NSString *content = [_pString stringByMatching:regex];
    return content;
}

//获取Group的id列表
+ (NSMutableArray*)getGroupListFromContent:(NSString*)content {
    NSString *childreContent = [content stringByMatching:@"children =(?:.|[\r\n])*?;"];
    childreContent = [childreContent stringByReplacingOccurrencesOfString:@"children = (" withString:@""];
    childreContent = [childreContent stringByReplacingOccurrencesOfString:@");" withString:@""];
    NSArray *childrenList = [childreContent componentsSeparatedByString:@","];
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < [childrenList count]; i++) {
        NSString *str = [childrenList objectAtIndex:i];
        NSString *note = [str stringByMatching:@"/.*?/"];
        if (!note) {
            break;
        }
        str = [str stringByReplacingOccurrencesOfString:note withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"\t" withString:@""];
        str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        
        note = [note stringByReplacingOccurrencesOfString:@"/" withString:@""];
        note = [note stringByReplacingOccurrencesOfString:@"*" withString:@""];
        note = [note stringByReplacingOccurrencesOfString:@"," withString:@""];
        note = [note stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (str && note) {
            NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:note,@"name",str,@"id", nil];
            if (dict) {
               [resultArray addObject:dict];
            }
        }
    }
    return resultArray;
}

#pragma mark end<<<<<<<<<<<<<<<<<<<< -

#pragma mark - 修改应用信息
//修改生成app的文件名
+(bool)modifyProductName:(NSString*)appName projectPath:(NSString*)path
{
    //修改成中文名称会导致不能上架
    return YES;
    
    path = [NSString stringWithFormat:@"%@",[self getPbxprojPath:path]];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
        return NO;
    }
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSString *handleStr = nil;
    if (str == nil) {
        return NO;
    }
    else{
        NSString *temp = [str stringByReplacingOccurrencesOfRegex:@"\"<" withString:@"\"&lt;"];
        NSString *temp1 = [temp stringByReplacingOccurrencesOfRegex:@"<.*?>" withString:@" "];
        NSString *temp2 = [temp1 stringByReplacingOccurrencesOfRegex:@"&lt;" withString:@"<"];
        handleStr = [temp2 stringByReplacingOccurrencesOfRegex:@"&gt;" withString:@">"];
       // NSLog(@"\n File: \n %@",handleStr);
    }
    
    NSString *keyWord = [NSString stringWithFormat:@"PRODUCT_NAME = .*\n"];
    
    NSString *resultStr = [handleStr stringByReplacingOccurrencesOfRegex:keyWord withString:[NSString stringWithFormat:@"PRODUCT_NAME = \"%@\";\n",appName]];

    //NSLog(@"\n\n\n\n\n\n\n%@",resultStr);
    
    [resultStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

//修改程序名称
+(bool)modifyAppName:(NSString*)appName projectPath:(NSString*)path {
    path = [NSString stringWithFormat:@"%@",[self getPlistPath:path]];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
        return NO;
    }
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    // NSString *handleStr = nil;
    if (str == nil) {
        return NO;
    }
    
    NSString *keyWord = [NSString stringWithFormat:@"<key>CFBundleDisplayName</key>.*?\n.*?</string>"];
    
    NSString *resultStr = [str stringByReplacingOccurrencesOfRegex:keyWord withString:
                           [NSString stringWithFormat:@"<key>CFBundleDisplayName</key>\n\t<string>%@</string>",appName]];
    
    [resultStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

//修改程序BundleID
+(bool)modifyBundleID:(NSString*)bundleName projectPath:(NSString*)path
{
    path = [NSString stringWithFormat:@"%@",[self getPlistPath:path]];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
//        NSLog(@"File not exist!");
        return NO;
    }
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
   // NSString *handleStr = nil;
    if (str == nil) {
//        NSLog(@"NIL");
        return NO;
    }
    //NSLog(@"%@",str);
    
    NSString *keyWord = [NSString stringWithFormat:@"<key>CFBundleIdentifier</key>.*?\n.*?</string>"];
    
    //NSLog(@"%@",[str stringByMatching:keyWord]);
    
    NSString *resultStr = [str stringByReplacingOccurrencesOfRegex:keyWord withString:
                                    [NSString stringWithFormat:@"<key>CFBundleIdentifier</key>\n\t<string>%@</string>",bundleName]];
    
    //NSLog(@"\n\n\n\n\n\n\n%@",resultStr);
    
    //支付宝支付完成返回需要bundle id
    resultStr = [resultStr stringByReplacingOccurrencesOfString:@"XAPPS123X_ALIPAY_BUNDLEID" withString:bundleName];
    
    [resultStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

//修改App Version
+(bool)modifyAppVersion:(NSString*)appVersion projectPath:(NSString*)path
{
    appVersion = [appVersion lowercaseString];
    appVersion = [appVersion stringByReplacingOccurrencesOfString:@"v" withString:@""];
    
    path = [NSString stringWithFormat:@"%@",[self getPlistPath:path]];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
//        NSLog(@"File not exist!");
        return NO;
    }
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    // NSString *handleStr = nil;
    if (str == nil) {
//        NSLog(@"NIL");
        return NO;
    }
    //NSLog(@"%@",str);
    
    //--------app version
    NSString *keyWord = [NSString stringWithFormat:@"<key>CFBundleVersion</key>.*?\n.*?</string>"];
    
   // NSLog(@"%@",[str stringByMatching:keyWord]);
    
    NSString *resultStr = [str stringByReplacingOccurrencesOfRegex:keyWord withString:
                           [NSString stringWithFormat:@"<key>CFBundleVersion</key>\n\t<string>%@</string>",appVersion]];
    
    //----------build version
    keyWord = [NSString stringWithFormat:@"<key>CFBundleShortVersionString</key>.*?\n.*?</string>"];
    
   // NSLog(@"%@",[resultStr stringByMatching:keyWord]);
    
    resultStr = [resultStr stringByReplacingOccurrencesOfRegex:keyWord withString:
                           [NSString stringWithFormat:@"<key>CFBundleShortVersionString</key>\n\t<string>%@</string>",appVersion]];
    
    [resultStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

//修改SDK Version
+(bool)modifySDKLibraryVersion:(NSString*)sdkVersion projectPath:(NSString*)path
{
    path = [NSString stringWithFormat:@"%@",[self getPlistPath:path]];
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
//        NSLog(@"File not exist!");
        return NO;
    }
    
//    if (sdkVersion.intValue < 1 || sdkVersion.intValue > 6) {
//        NSLog(@"SDK Version Incorrect!!");
//        return NO;
//    }
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    // NSString *handleStr = nil;
    if (str == nil) {
//        NSLog(@"NIL");
        return NO;
    }
//    NSLog(@"%@",str);
    
    NSString *keyWord = [NSString stringWithFormat:@"<key>CFBundleInfoDictionaryVersion</key>.*?\n.*?</string>"];
    
    //NSLog(@"%@",[str stringByMatching:keyWord]);
    
    NSString *resultStr = [str stringByReplacingOccurrencesOfRegex:keyWord withString:
                           [NSString stringWithFormat:@"<key>CFBundleInfoDictionaryVersion</key>\n\t<string>%@</string>",sdkVersion]];
    
    //NSLog(@"\n\n\n\n\n\n\n%@",resultStr);
    
    [resultStr writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}




//修改工程IPHONEOS_DEPLOYMENT_TARGET版本
+(bool)modifyDeploymentVersion:(NSString*)deploymentVersion projectPath:(NSString*)path
{
    NSString *pPath = nil;
    if (path == nil) {
        pPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/project.pbxproj"];
    }
    else
    {
        //根据工程目录获取配置文件位置
        pPath = [self getPbxprojPath:path];
    }
    
    //文件不存在，不能修改
    if (pPath == nil) {
        return NO;
    }
    
    NSString *handleStr = nil;
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:pPath encoding:NSUTF8StringEncoding error:nil];
    if (str == nil) {
//        NSLog(@"NIL");
        return NO;
    }
    else{
        NSString *temp = [str stringByReplacingOccurrencesOfRegex:@"\"<" withString:@"\"&lt;"];
        NSString *temp1 = [temp stringByReplacingOccurrencesOfRegex:@"<.*?>" withString:@" "];
        NSString *temp2 = [temp1 stringByReplacingOccurrencesOfRegex:@"&lt;" withString:@"<"];
        handleStr = [temp2 stringByReplacingOccurrencesOfRegex:@"&gt;" withString:@">"];
        //NSLog(@"\n File: \n %@",handleStr);
    }
    
    NSString *keyWord = @"IPHONEOS_DEPLOYMENT_TARGET =.*?;";

    //NSInteger count = [[handleStr arrayOfCaptureComponentsMatchedByRegex:keyWord] count];
    //NSLog(@"%ld",count);
    NSString *resultStr = [handleStr stringByReplacingOccurrencesOfRegex:keyWord withString:
                           [NSString stringWithFormat:@"IPHONEOS_DEPLOYMENT_TARGET = %@;",deploymentVersion]];

    [resultStr writeToFile:pPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    return YES;
}

//修改工程的CODE_SIGN_IDENTITY
+(bool)modifyMobileProvision:(NSString*)path  profilePath:(NSString*)profilePath
{
    NSString *pPath = nil;
    if (path == nil) {
        pPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/project.pbxproj"];
    }
    else
    {
        //根据工程目录获取配置文件位置
        pPath = [self getPbxprojPath:path];
    }
    
    //文件不存在，不能修改
    if (pPath == nil) {
        return NO;
    }
    
    NSString *handleStr = nil;
    
    NSString *str = [[NSString alloc] initWithContentsOfFile:pPath encoding:NSUTF8StringEncoding error:nil];
    if (str == nil) {
//        NSLog(@"NIL");
        return NO;
    }
    else{
        NSString *temp = [str stringByReplacingOccurrencesOfRegex:@"\"<" withString:@"\"&lt;"];
        NSString *temp1 = [temp stringByReplacingOccurrencesOfRegex:@"<.*?>" withString:@" "];
        NSString *temp2 = [temp1 stringByReplacingOccurrencesOfRegex:@"&lt;" withString:@"<"];
        handleStr = [temp2 stringByReplacingOccurrencesOfRegex:@"&gt;" withString:@">"];
       //NSLog(@"\n File: \n %@",handleStr);
        //[usefulStr writeToFile:pName atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    
    NSMutableDictionary *dict = [self readProfile:profilePath];
    NSString *uuid = [dict objectForKey:@"uuid"];
    NSString *teamName = [dict objectForKey:@"teamname"];
    NSString *modeName = @"iPhone Distribution";
    
    if ([[dict objectForKey:@"mode"] isEqualToString:@"debug"]) {
        modeName = @"iPhone Developer";
    }
    
    //Profiles
    NSString *key1 = @"PROVISIONING_PROFILE\\s*=\\s*\".*?\"\\s*;";
    handleStr = [handleStr stringByReplacingOccurrencesOfRegex:key1 withString:[NSString stringWithFormat:@"PROVISIONING_PROFILE = \"%@\";",uuid]];
    
    NSString *key2 = @"\"PROVISIONING_PROFILE\\[sdk=iphoneos\\*\\]\"\\s*=\\s*\".*?\"\\s*;";
    handleStr = [handleStr stringByReplacingOccurrencesOfRegex:key2 withString:[NSString stringWithFormat:@"\"PROVISIONING_PROFILE[sdk=iphoneos*]\" = \"%@\";",uuid]];
    
    
    //Identity
    NSString *key3 = @"CODE_SIGN_IDENTITY\\s*=\\s*\".*?\"\\s*;";
    handleStr = [handleStr stringByReplacingOccurrencesOfRegex:key3 withString:[NSString stringWithFormat:@"CODE_SIGN_IDENTITY = \"%@: %@\";",modeName,teamName]];
    
    NSString *key4 = @"\"CODE_SIGN_IDENTITY\\[sdk=iphoneos\\*\\]\"\\s*=\\s*\".*?\"\\s*;";
    handleStr = [handleStr stringByReplacingOccurrencesOfRegex:key4 withString:[NSString stringWithFormat:@"\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"%@: %@\";",modeName,teamName]];
    
    
   //NSLog(@"\n\n\n\n\n\n\n\n\n%@",resultStr);
    
    [handleStr writeToFile:pPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    
    //复制mobileprovisions到相应目录
    NSFileManager *fm = [NSFileManager defaultManager];
    
    NSString *gpPath = [NSString stringWithFormat:@"%@/Library/MobileDevice/Provisioning Profiles/%@.mobileprovision",NSHomeDirectory(),uuid];
    
    [fm copyItemAtPath:profilePath toPath:gpPath error:nil];
    
    //修改application-identify
//    NSString *appIDName = [dict objectForKey:@"AppIDName"];
//    PathParser *pp = [PathParser sharePathParser];
//    [self modifyBundleID:[NSString stringWithFormat:@"%@.%@",pp.appBundleIdHeadString,appIDName] projectPath:path];
//    
    NSString *bundleId = [dict objectForKey:@"bundleId"];
    [self modifyBundleID:bundleId projectPath:path];
    
    return YES;
}

+ (NSMutableDictionary*)readProfile:(NSString*)path {
    
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:path]) {
        NSLog(@"Warming:File not exist: %s\n",[path UTF8String]);
        return nil;
    }
    
    NSString *fileString = [[NSString alloc] initWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];
	NSScanner *scanner = [[NSScanner alloc] initWithString:fileString];
    
    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] init];

	if ([scanner scanUpToString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" intoString:NULL]) {
	    NSString *plistString;
	    if ([scanner scanUpToString:@"</plist>" intoString:&plistString]) {
            NSDictionary *plist = [[plistString stringByAppendingString:@"</plist>"] propertyList];
          
            if ([plist valueForKeyPath:@"ProvisionedDevices"]) {
                if ([[plist valueForKeyPath:@"Entitlements.get-task-allow"] boolValue]) {
                    NSLog(@"debug \n");
                    [resultDict setObject:@"debug" forKey:@"mode"];
                } else {
                    NSLog(@"ad-hoc \n");
                    [resultDict setObject:@"ad-hoc" forKey:@"mode"];
                }
            } else {
                NSLog(@"appstore \n");
                [resultDict setObject:@"appstore" forKey:@"mode"];
            }
//		
//            [resultDict setObject:[plist valueForKeyPath:@"UUID"] forKey:@"uuid"];
//            //TeamName
//            [resultDict setObject:[plist valueForKeyPath:@"TeamName"] forKey:@"teamname"];
            
            if ([plist valueForKeyPath:@"UUID"]) {
                [resultDict setObject:[plist valueForKeyPath:@"UUID"] forKey:@"uuid"];
            }
            
            //TeamName
            if ([plist valueForKeyPath:@"TeamName"]) {
                [resultDict setObject:[plist valueForKeyPath:@"TeamName"] forKey:@"teamname"];
            }
            
            if ([plist valueForKeyPath:@"AppIDName"]) {
                [resultDict setObject:[plist valueForKeyPath:@"AppIDName"] forKey:@"AppIDName"];
            }
            
            //bundleId
            if ([plist valueForKey:@"Entitlements"]) {
                NSDictionary *eDict = [plist valueForKey:@"Entitlements"];
                NSString *applicationId = [eDict valueForKey:@"application-identifier"];
                NSArray *aArray = [applicationId componentsSeparatedByString:@"."];
                if ([aArray count] > 2) {
                    NSString *bundleId = [applicationId stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@.",[aArray objectAtIndex:0]] withString:@""];
                    [resultDict setObject:bundleId forKey:@"bundleId"];
                }
            }
            
        }   
	}
    
    return resultDict;

}

@end












